
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Vector;

import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;
import javax.swing.plaf.metal.MetalBorders.TextFieldBorder;
import javax.swing.table.DefaultTableModel;
import javax.swing.JLabel;


public class actionToDatabase extends JFrame {

	private JPanel contentPane;
	private String[] fields;
	private ArrayList<String> colName;
	private PreparedStatement preparedStatement = null;
	static JTextField[] tField = null;
	static StringBuilder addQuery;;
	

	/**
	 * Create the frame.
	 * @throws SQLException 
	 */
	public actionToDatabase(ResultSet result, Connection conn) throws SQLException {
		int i;
		
		// = new ArrayList<String>();
		JButton addButt;
		JButton disButt;
		JButton updButt;
		createWindow(100, 100, 525, 350, "Add to Database");
		
		
		//try {
		colName = getColumnNames(result);
		int size = colName.size();
		tField = addComponents(colName, size);
		int tSize = tField.length;
		fields = new String[tSize];
		addButt = addButton(45, 235, 140, 20, "Add to Database");
		updButt = addButton(45, 260, 140, 20, "Update Database");
		disButt = addButton(208, 235, 140, 20, "Discard Changes");
		
		    ActionListener textListener = textListener();
		    for (i = 0; i < tSize; i++){
		        tField[i].addActionListener(textListener);
		    }
		    
		    disButt.addActionListener(disButtListener());
		    addButt.addActionListener(addButtListener(result, conn));
		    	    
		   
		setLocationRelativeTo(getRootPane()); 
		
	}
	
public static ArrayList<String> getColumnNames(ResultSet result)
		throws SQLException {
	ArrayList<String> columnNames = new ArrayList<String>();
 try
 {
	ResultSetMetaData metaData = result.getMetaData();
	int columnCount = metaData.getColumnCount();
    	for (int column = 1; column <= columnCount; column++) 
    	{
    		columnNames.add(metaData.getColumnName(column));
    	}
 } 
 catch (SQLException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
    
    return columnNames;
}

public void createWindow(int w, int x, int y, int z, String title)
{
	contentPane = new JPanel();
	setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	setBounds(100, 100, 425, 350);
	
    contentPane.setBounds(w,x,y,z);
    contentPane.setName(title);
	contentPane.setPreferredSize(getPreferredSize());
	setContentPane(contentPane);
	contentPane.setLayout(null);
	   
}

public JTextField[] addComponents(ArrayList<String> colNames, int size) throws SQLException
{
	ArrayList<Object[]> data = new ArrayList<Object[]>();
	int q;
	int y = 46;
	JLabel[] labels = new JLabel[size];
	final JTextField[] textFields = new JTextField[size];
	for(int i = 0; i < size; i++)
	{
		labels[i] = new JLabel(colNames.get(i) + ":");
		textFields[i] = new JTextField();
		textFields[i].setName(i + "");
		labels[i].setBounds(45, y, 69, 20);
		textFields[i].setBounds(208, y, 146, 20);
		contentPane.add(labels[i]);
		contentPane.add(textFields[i]);
		y= y+20;
		 
	}
		
	return textFields;

}

public JButton addButton(int x, int y, int w, int h, String name)
{
	JButton button = new JButton(name);
	button.setBounds(x, y, w, h);
	contentPane.add(button);
	
	return button;
	
}

public ActionListener textListener()
{
ActionListener listener = new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
      JTextField field = (JTextField) e.getSource();
      String str = field.getText();
      int index = Integer.parseInt(field.getName());
      fields[index] = str;
      field.setEnabled(false);
    }
};

return listener;
}

public void resetBoard()
{
	for(int i = 0; i < tField.length; i++)
	{
		tField[i].setText("");
		tField[i].setEnabled(true);
	}
}

public ActionListener disButtListener()
{
ActionListener listener = new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
      JButton addButt = (JButton) e.getSource();
      resetBoard();
    }
};
return listener;
}

public ActionListener addButtListener(final ResultSet result, final Connection conn) throws SQLException
{
	addQuery = new StringBuilder("");
	final ResultSetMetaData rsMetaData = result.getMetaData();
	final String table = rsMetaData.getTableName(1);
	
ActionListener listener = new ActionListener() {
    @SuppressWarnings("null")
	@Override
    public void actionPerformed(ActionEvent e) {

      JButton addButt = (JButton) e.getSource();
      if(isTextDisabled() == true)
      {   
    	  //("insert into laptop values ('Apple',2000,2,2.00,450,12,6)");
		  String query;
    	  addQuery.append("insert into " + table + " values (");
    	  
    	  for(int m = 0; m < fields.length-1; m++)
    	  {
    		  try {
    			  
    			System.out.println("col = " + rsMetaData.getColumnTypeName(m+1));
				if(rsMetaData.getColumnTypeName(m+1).equals("INT") || rsMetaData.getColumnTypeName(m+1).equals("FLOAT"))
				 {
					System.out.println("field = " + fields[m]);
					addQuery.append(fields[m] + ",");
				 }
				else
				{
					System.out.println("field = " + fields[m]);
					addQuery.append("'" + fields[m] + "',");
				}
			} catch (SQLException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
    		  
    	  }
    	  try {
			if(rsMetaData.getColumnTypeName(colName.size()-1).equals("INT") || rsMetaData.getColumnTypeName(colName.size()-1).equals("FLOAT"))
			  {
				addQuery.append(fields[fields.length-1] + ")");
			  }
			else
			{
				addQuery.append("'" + fields[fields.length-1] + "')");
			}
		} catch (SQLException e2) {
			// TODO Auto-generated catch block
			e2.printStackTrace();
		}
    	  
    	  
    			query = addQuery.toString();
    			System.out.println(query);
    			
    			try {
    				//preparedStatement = conn.prepareStatement("insert into laptop values ('Apple',2000,2,2.00,450,12,6)");
    				preparedStatement = conn.prepareStatement(query);
    				preparedStatement.executeUpdate();
    				//state = conn.createStatement();
    				//String sql = "INSERT INTO laptop (make, price, quantity, speed, hdd, screen, sku) VALUES ('Apple',2000,2,2.00,450,12,6) " +
    	                   // "VALUES ('Apple',2000,2,2.00,450,12,6);";

    				
 
    				JOptionPane.showMessageDialog (null, "Item Added", "Message", JOptionPane.ERROR_MESSAGE);
    			} catch (SQLException e1) {
    				// TODO Auto-generated catch block
    				e1.printStackTrace();
    			}
    		
    	 // System.out.println(query);
    	  //fields[fields.length-1] 
    	  //query = "INSERT INTO 'sql322002'.'laptop"
    			  //INSERT INTO `sql322002`.`laptop` (`make`, `price`, `quantity`, `speed`, `hdd`, `screen`, `sku`) VALUES ('Apple', '2000', '2', '2.00', '400', '12', '3');
      }
      else
      {
    	  JOptionPane.showMessageDialog (null, "Message", "Error: Item not added", JOptionPane.ERROR_MESSAGE);
      }
    }
};
return listener;
}

public static boolean isTextDisabled()
{
	boolean bol = true;
	for(int i = 0; i < tField.length; i++)
	{
		if(tField[i].isEnabled() == true)
		{
			bol = false;
		}
	}
	return bol;
}

public static StringBuilder getAddQuery()
{
	return addQuery;
}


}


